package com.gxc.datacore.query.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gxc.datacore.metadata.domain.Column;
import com.gxc.datacore.metadata.domain.Table;
import com.gxc.datacore.metadata.service.TableService;
import com.gxc.datacore.metadata.util.SqlDaoUtil;
import com.gxc.datacore.query.service.DataAccessService;
import com.gxc.datacore.query.service.DataQueryService;
import com.gxc.datacore.query.service.DataTranslateService;
import com.gxc.dbcore.dao.SqlDao;
import com.gxc.dbcore.util.BeanMap;
import com.gxc.dbcore.util.CompareItem;
import com.gxc.dbcore.util.CompareType;
import com.gxc.dbcore.util.PageInfo;
import com.gxc.dbcore.util.PageList;
import com.gxc.webcore.util.ContextUtil;
import com.gxc.webcore.util.StringUtil;

@Service
public class DataQueryServiceImpl implements DataQueryService {

	@Autowired
	private DataAccessService dataAccessService;
	@Autowired
	private DataTranslateService dataTranslateService;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List query(String user_id, String table_id, Map params,
			boolean translate) {
		TableService tableService = (TableService) ContextUtil
				.getBean("datacoreTableService");
		Table table = tableService.retrieve(table_id);
		List columns = dataAccessService.getColumnList(user_id, table_id);

		// 判断结果列是否为空
		if (columns == null || columns.size() == 0) {
			return null;
		}
		// 参数构建
		Map queryParams = buildParams(table, columns, params);

		// 查询
		SqlDao sqlDao = SqlDaoUtil.getSqlDaoByTable(table);
		List list = sqlDao.selectList("datacore.dataquery.query", queryParams);

		// 翻译
		if (translate) {
			list = dataTranslateService.translate(columns, list);
		}
		return list;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public PageList query(String user_id, String table_id, Map params,
			boolean translate, PageInfo pageInfo) {
		TableService tableService = (TableService) ContextUtil
				.getBean("datacoreTableService");
		Table table = tableService.retrieve(table_id);
		List columns = dataAccessService.getColumnList(user_id, table_id);

		// 判断结果列是否为空
		if (columns == null || columns.size() == 0) {
			PageList pageList = new PageList();
			pageList.setPageInfo(pageInfo);
			return pageList;
		}
		// 参数构建
		Map queryParams = buildParams(table, columns, params);

		// 查询
		SqlDao sqlDao = SqlDaoUtil.getSqlDaoByTable(table);
		PageList pageList = sqlDao.selectPageList("datacore.dataquery.query",
				"datacore.dataquery.count", queryParams, pageInfo);

		// 翻译
		if (translate) {
			pageList.setList(dataTranslateService.translate(columns,
					(List<BeanMap>) pageList.getList()));
		}

		return pageList;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List query(String user_id, String table_id, Map params,
			boolean translate, int offset, int limit) {
		TableService tableService = (TableService) ContextUtil
				.getBean("datacoreTableService");
		Table table = tableService.retrieve(table_id);
		List columns = dataAccessService.getColumnList(user_id, table_id);

		// 判断结果列是否为空
		if (columns == null || columns.size() == 0) {
			return null;
		}
		// 参数构建
		Map queryParams = buildParams(table, columns, params);

		// 查询
		SqlDao sqlDao = SqlDaoUtil.getSqlDaoByTable(table);
		RowBounds rowBounds = new RowBounds(offset, limit);
		List list = sqlDao.selectList("datacore.dataquery.query", queryParams,
				rowBounds);

		// 翻译
		if (translate) {
			list = dataTranslateService.translate(columns, list);
		}
		return list;
	}

	/**
	 * 参数构建
	 * 
	 * @param table
	 * @param columns
	 * @param params
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Map buildParams(Table table, List columns, Map params) {
		Map queryParams = new HashMap();
		// 模式名和表名
		queryParams.put("schema_name", table.getSchema_name());
		queryParams.put("table_name", table.getTable_name());

		// 结果列
		String resultColumns = buildResultColumns(columns);
		queryParams.put("resultColumns", resultColumns);

		// 查询条件
		List conditionList = buildConditions(columns, params);
		queryParams.put("conditionList", conditionList);

		// 查询条件个数
		if (conditionList.size() > 0) {
			queryParams.put("conditionNum", conditionList.size());
		}

		return queryParams;
	}

	/**
	 * 构建结果列
	 * 
	 * @param columns
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private String buildResultColumns(List columns) {
		if (columns == null) {
			return null;
		}
		// 结果列
		String resultColumns = "";
		for (int i = 0; i < columns.size(); i++) {
			if (i != 0) {
				resultColumns += ",";
			}
			resultColumns += ((Column) columns.get(i)).getColumn_name();
		}
		return resultColumns;
	}

	/**
	 * 构建查询条件
	 * 
	 * @param table
	 * @param columns
	 * @param params
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private List<CompareItem> buildConditions(List columns, Map params) {
		if (columns == null || params == null) {
			return null;
		}
		List<CompareItem> conditionList = new ArrayList();
		for (Column column : (List<Column>) columns) {
			if (column.getIs_query() == 1) {
				// 设置默认比较类型
				if (!CompareType.isValid(column.getCompare_type())) {
					column.setCompare_type(1);
				}
				if (column.getCompare_type() == CompareType.BETWEEN) {
					// 范围查询
					String value1 = (String) params.get(column.getColumn_name()
							+ "_start");
					String value2 = (String) params.get(column.getColumn_name()
							+ "_end");
					if (!StringUtil.isTrimEmpty(value1)
							|| !StringUtil.isTrimEmpty(value2)) {
						CompareItem item = new CompareItem();
						item.setColumnName(column.getColumn_name());
						item.setCompareType(CompareType.BETWEEN);
						item.setCompareValue(value1 == null ? null : value1
								.trim());
						item.setCompareValue2(value2 == null ? null : value2
								.trim());
						conditionList.add(item);
					}
				} else {
					// 单值查询
					if (!StringUtil.isTrimEmpty((String) params.get(column
							.getColumn_name()))) {
						CompareItem item = new CompareItem();
						item.setColumnName(column.getColumn_name());
						item.setCompareType(column.getCompare_type());
						item.setCompareValue(params
								.get(column.getColumn_name()).toString().trim());
						conditionList.add(item);
					}
				}
			}
		}
		return conditionList;
	}

}